<script setup>
import { computed, ref, reactive } from 'vue'
import { getByRoomNumberService, addRepairService, finishRepairService, deleteRepairService } from '@/api/repair'
import { ElMessage } from 'element-plus'
import { getUserInfo } from '@/api/userInfo'
import { findWorkerService } from '@/api/worker'
import { deleteFileService } from '@/api/file'
// import { globals } from "@/main";

// const serverUrl = ref(globals.$config?.serverUrl + "/files/uploadFile")

const tableData = reactive([])

//搜索列表内容
const search = ref('')
const filterTableData = computed(() =>
    tableData.filter(
        (data) =>
            !search.value ||
            data.detail.toLowerCase().includes(search.value.toLowerCase())
    )
)

// const roomNumber = ref('')
const form = reactive({ 'roomNumber': '', 'detail': '', 'photo':'' })

async function getRepairList() {
    tableData.length = 0
    //获取token信息携带的房间号
    let result = await getUserInfo()
    form.roomNumber = result.data.userId
    // console.log(roomNumber.value)
    let res = await getByRoomNumberService(form.roomNumber)
    // console.log(res)
    for (let i = 0; i < res.data.length; i++) {
        // let name = await (await findWorkerService(res.data[i].workerId)).data.name
        // res.data.append('workerName',name)
        tableData.push(res.data[i])
    }
}

getRepairList()


const dialogFormVisible = ref(false)

const openForm = () => {
    dialogFormVisible.value = true
    form.detail = ''
    if(uploadRef.value){
        uploadRef.value.clearFiles()
    }
    
}

const uploadRef = ref()
const headers = { Authorization: localStorage.getItem('Authorization') }
// const url = ref('')



// const submitUpload = () => {
//     if (uploadRef.value !== null) {
//         uploadRef.value.submit()
//         // console.log(result)
//     } else {
//         ElMessage.error('上传列表为空')
//     }
// }
const removeFile = async () => {
    if(form.photo){
        await deleteFileService(form.photo)
    }
    uploadRef.value.clearFiles()
    form.photo = ''
    ElMessage.info("移除成功！")
}
const uploadSuccess = (res) => {
    ElMessage.success("上传成功！")
    // uploadRef.value.clearFiles()
    // console.log(res.data)
    form.photo = res.data
    // console.log(form.photo)
    // getTable()
}
const uploadError = () => {
    ElMessage.error("上传失败！")
    uploadRef.value.clearFiles()
}
const handleExceed = () => {
    ElMessage.error("上传文件超出限制，请重新选择")
    uploadRef.value.clearFiles()
}

const addRepair = async () => {
    await addRepairService(form)
    ElMessage.success('维修申请成功，请注意查看进度')
    getRepairList()
    dialogFormVisible.value = false
}

const handPass = async (row) => {
    await finishRepairService(row.id)
    ElMessage.success('已成功验收，如有疑问请前往物业办公室')
    getRepairList()
}

const deleteRepair = async (row) => {
    await deleteRepairService(row.id)
    ElMessage.success('您的维修申请已成功撤销')
    getRepairList()
}

const classObje = (status) => {
    if (status === 1) {
        return { color: "pink" }
    } else if (status === 0) {
        return { color: "lightgray" }
    } else if (status === 2) {
        return { color: "#13ce66" }
    }
}

const rules = {
    detail: [{ required: true, message: '描述不可为空！', trigger: 'blur' }]
}

</script>

<template>
    <div style="width: 100%;padding:25px;">
        <div style="display: flex;padding-bottom: 20px;padding-top: 10px;">
            <el-button type="primary" @click="openForm"
                style="width: 70px;background-color: rgb(19, 179, 232);color: white;">申请维修</el-button>
            <el-input v-model="search" placeholder="查找" style="width: 200px;margin-left:100vh;" />
        </div>
        <el-table :data="filterTableData" border style="min-width:calc(100vh - 200px)">
            <el-table-column label="ID" prop="id" width="70px" sortable />
            <!-- <el-table-column label="门牌号" prop="roomNumber" sortable width="120px" /> -->
            <el-table-column label="详情描述" prop="detail" />
            <el-table-column label="图片" prop="photo">
                <template #default="scope">
                    <el-image :src="scope.row.photo" :preview-src-list="[scope.row.photo]" preview-teleported="true" style="height: 75px;"/>
                </template>
            </el-table-column>
            <el-table-column label="报修时间" prop="time"/>
            <el-table-column label="状态" sortable prop="status" width="90px">
                <template #default="scope">
                    <span :style="classObje(scope.row.status)">
                        <i v-if="scope.row.status === 0">待审核</i>
                        <i v-if="scope.row.status === 1">待维修</i>
                        <i v-if="scope.row.status === 2">已完成</i>
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="维修员" prop="workerId" width="90px" />
            <el-table-column label="操作" align="center" width='200px'>
                <template #default="scope">
                    <el-button v-if="scope.row.status === 1" @click="handPass(scope.row)"
                        style="color:#13ce66">确认验收</el-button>
                    <el-button v-if="scope.row.status === 0" @click="deleteRepair(scope.row)"
                        style="color:#a0a0a0">撤销申请</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <el-dialog v-model="dialogFormVisible" title="提交申请">
        <div style="margin-left: 140px;padding-bottom: 20px;padding-top: 20px;">
            <el-upload ref="uploadRef" action="http://localhost:9191/files/uploadFile"
                :on-success="uploadSuccess" :on-error="uploadError" :limit="1" :on-exceed="handleExceed"
                :on-remove="removeFile" :headers="headers">
                <template #trigger>
                    <el-button type="primary">上传文件</el-button>
                </template>
                <template #tip>
                    <div class="el-upload__tip">
                        请上传500kb以内的jpg/png文件
                    </div>
                </template>
            </el-upload>
        </div>
        <el-form :model="form" :rules="rules">
            <el-form-item label="描述" :label-width="140" prop="detail">
                <el-input v-model="form.detail" type="textarea" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addRepair">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>